﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ECP.Utilities.Controls;
using ECP.Model;
using ECP.Service.Utilities;
using ECP.Utilities;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;

namespace ECP.Client.Module
{
    public partial class ModuleConfigFrm : FormBase, IModelInfo
    {
        private string currentEntityID;
        private DataTable DTModule;
        private bool IsUserClick;
        public string OldEntityID;
        private bool PermissionAccess;
        private bool PermissionEdit;
        public ModuleConfigFrm()
        {
            this.DTModule = new DataTable(BaseModuleTable.TableName);
            this.OldEntityID = string.Empty;
            this.currentEntityID = string.Empty;
            InitializeComponent();
            this.DisplayType = DisplayTypes.Dialog;
        }


        public ModuleConfigFrm(string currentID)
            : this()
        {
            this.CurrentEntityID = currentID;
            this.OldEntityID = currentID;
        }

        public string CurrentEntityID
        {
            get
            {
                if (this.tvModule.FocusedNode != null)
                {
                    this.currentEntityID = this.tvModule.FocusedNode.GetValue(colParentID).ToString();
                }
                return this.currentEntityID;
            }
            set
            {
                this.currentEntityID = value;
            }
        }
        public override string ModelCode
        {
            get { return this.GetType().FullName; }
        }

        public override string ModelName
        {
            get { return this.Text; }
        }

        public override void StartModel()
        {
            base.StartModel();
        }

        public IList<PermissionInfo> Permissions
        {
            get
            {
                return new List<PermissionInfo>()
                {
                    new PermissionInfo("ModuleConfig.Access", "模块设置") ,
                    new PermissionInfo("ModuleConfig.Edit", "编辑设置") 
                   
                };
            }
        }
        private void EntityToDataTable(TreeListNode TreeNode)
        {
            foreach (DataRow row in this.DTModule.Select(BaseModuleTable.FieldID + "='" + TreeNode.GetValue(colParentID).ToString() + "'"))
            {
                row[BaseModuleTable.FieldEnabled] = TreeNode.Checked ? 1 : 0;
            }
            for (int i = 0; i < TreeNode.Nodes.Count; i++)
            {
                this.EntityToDataTable(TreeNode.Nodes[i]);
            }
        }
        private void BatchSave()
        {
            for (int i = 0; i < this.tvModule.Nodes.Count; i++)
            {
                this.EntityToDataTable(this.tvModule.Nodes[i]);
            }
            ServiceManager.Instance.ModuleService.BatchSave(base.UserInfo, this.DTModule);
            if (BaseSystemInfo.ShowInformation)
            {
                MessageBox.Show(AppMessage.MSG0011, AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
        private void LoadTree()
        {
            this.tvModule.BeginUpdate();
            this.tvModule.Nodes.Clear();
            BaseInterfaceLogic.LoadTreeNodes(this.DTModule, BaseModuleTable.FieldID, BaseModuleTable.FieldParentID, BaseModuleTable.FieldFullName, this.tvModule);

      
            if (this.tvModule.Nodes.Count > 0)
            {
                this.tvModule.Nodes[0].Expanded = true;
                DefaultExpand(this.tvModule.Nodes[0]);

            }

            BaseInterfaceLogic.FindTreeNode(this.tvModule, this.OldEntityID, this.colParentID);

            if (BaseInterfaceLogic.TargetNode != null)
            {
                this.tvModule.FocusedNode = BaseInterfaceLogic.TargetNode;                
            }          
            this.tvModule.EndUpdate();
        }


        private void DefaultExpand(TreeListNode node)
        {
            var str = node.GetValue(colExpand).ToString();
            var strEnable = node.GetValue(colEnabled).ToString();
            if (str == "1")
            {
                node.Expanded = true;

            }
            else
            {
                node.Expanded = false;
            }
            if (strEnable == "1")
            {
                node.Checked = true;
            }
            else
            {
                node.Checked = false;
            }
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                DefaultExpand(node.Nodes[i]);
            }

        }

        private void BindData(bool reloadTree)
        {
            if (reloadTree)
            {
                this.LoadTree();
            }
            if ((this.tvModule.FocusedNode == null) && (this.tvModule.Nodes.Count > 0))
            {
                if (this.CurrentEntityID.Length == 0)
                {
                    this.tvModule.FocusedNode = this.tvModule.Nodes[0];
                }
                else
                {
                    BaseInterfaceLogic.FindTreeNode(this.tvModule, this.CurrentEntityID, colParentID);
                    if (BaseInterfaceLogic.TargetNode != null)
                    {
                        this.tvModule.FocusedNode = BaseInterfaceLogic.TargetNode;
                        BaseInterfaceLogic.ExpandTreeNode(this.tvModule);
                    }
                }
                if (this.tvModule.FocusedNode != null)
                {
                    this.tvModule.FocusedNode.Expanded = true;
                }
            }
        }
        private void GetPermission()
        {
            this.PermissionAccess = base.IsAuthorized("ModuleConfig.Access");
            this.PermissionEdit = base.IsAuthorized("ModuleConfig.Edit");
        }
        private void SetControlState()
        {
            if (this.DTModule.DefaultView.Count == 0)
            {
                this.btnSelectAll.Enabled = false;
                this.btnInvertSelect.Enabled = false;
                this.btnBatchSave.Enabled = false;
            }
            else
            {
                this.btnSelectAll.Enabled = this.PermissionEdit;
                this.btnInvertSelect.Enabled = this.PermissionEdit;
                this.btnBatchSave.Enabled = this.PermissionEdit;
            }
        }
        private void SetTreeNodesTurnSelected(TreeListNode TreeNode)
        {
            if (TreeNode != null)
            {
                TreeNode.Checked = !TreeNode.Checked;
                for (int i = 0; i < TreeNode.Nodes.Count; i++)
                {
                    this.SetTreeNodesTurnSelected(TreeNode.Nodes[i]);
                }
            }
        }
        private void SetTreeNodesSelected(TreeListNode TreeNode, bool selected)
        {
            if (TreeNode != null)
            {
                TreeNode.Checked = selected;
                for (int i = 0; i < TreeNode.Nodes.Count; i++)
                {
                    this.SetTreeNodesSelected(TreeNode.Nodes[i], selected);
                }
            }
        }
        private void FormOnLoad()
        {
            this.IsUserClick = false;
            base.Localization(this);
            this.DTModule = ServiceManager.Instance.ModuleService.GetDT(base.UserInfo);
            this.GetPermission();
            this.SetControlState();
            this.BindData(true);
            this.IsUserClick = true;
        }
        private void btnBatchSave_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                this.BatchSave();
                ClientCache.Instance.DTMoule = ServiceManager.Instance.ModuleService.GetDT(base.UserInfo);
                ClientCache.Instance.DTUserMoule = ServiceManager.Instance.ModuleService.GetDT(base.UserInfo);
            }
            catch (Exception exception)
            {
                base.ProcessException(exception);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void btnInvertSelect_Click(object sender, EventArgs e)
        {
            this.IsUserClick = false;
            for (int i = 0; i < this.tvModule.Nodes.Count; i++)
            {
                this.SetTreeNodesTurnSelected(this.tvModule.Nodes[i]);
            }
            this.IsUserClick = true;
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            this.IsUserClick = false;
            for (int i = 0; i < this.tvModule.Nodes.Count; i++)
            {
                this.SetTreeNodesSelected(this.tvModule.Nodes[i], true);
            }
            this.IsUserClick = true;
        }

        private void tvModule_NodeChanged(object sender, DevExpress.XtraTreeList.NodeChangedEventArgs e)
        {
            if (e.Node.HasChildren)
            {
                e.Node.ImageIndex = 1;
                e.Node.SelectImageIndex = 1;
            }
            else
            {
                e.Node.SelectImageIndex = 2;
            }
        }

        private void ModuleConfigFrm_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                this.FormOnLoad();
            }
            catch (Exception exception)
            {
                base.ProcessException(exception);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void ModuleConfigFrm_KeyDown(object sender, KeyEventArgs e)
        {
            e.KeyCode.ToString();
            int keyValue = e.KeyValue;
            if ((keyValue != 0x2e) && (keyValue == 0x74))
            {
                this.FormOnLoad();
            }
        }

        private void tvModule_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            if (this.IsUserClick)
            {
                SetTreeNodesSelected(e.Node, e.Node.Checked);
            }
        }

        private void tvModule_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            if (this.IsUserClick && !this.PermissionEdit)
            {
                e.State = e.PrevState;
            }
        }


        /// <summary>
        /// 拖拽的节点
        /// </summary>
        private TreeListNode dragNode;
        /// <summary>
        /// 原始父节点
        /// </summary>
        private TreeListNode orgParentNode;
        /// <summary>
        /// 当前父节点
        /// </summary>
        private TreeListNode pNode = null;
        private int index;

        private void tvModule_DragDrop(object sender, DragEventArgs e)
        {
            TreeListHitInfo hitinfo = tvModule.CalcHitInfo(tvModule.PointToClient(new Point(e.X, e.Y)));
            TreeListNode node = hitinfo.Node;//当前点击的节点

            if (BaseInterfaceLogic.TreeNodeCanMoveTo(dragNode, node, colTreelist) && (!BaseSystemInfo.ShowInformation || (MessageBox.Show(AppMessage.Format(AppMessage.MSG0038, new string[] { this.dragNode.GetValue(colTreelist).ToString(), node.GetValue(colTreelist).ToString() }), AppMessage.MSG0000, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.No)))
            {
                this.Cursor = Cursors.WaitCursor;
                base.FormLoaded = false;
                ServiceManager.Instance.ModuleService.MoveTo(base.UserInfo, dragNode.GetValue(colParentID).ToString(), node.GetValue(colParentID).ToString());
                this.FormOnLoad();
                base.FormLoaded = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void tvModule_DragEnter(object sender, DragEventArgs e)
        {
            dragNode = tvModule.FocusedNode;
            orgParentNode = dragNode.ParentNode;
        }
    }
}